package com.martin.lib_base.model

import android.app.Activity
import android.content.Context
import androidx.fragment.app.Fragment
import com.martin.lib_base.interfaces.ILoading
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog
import dev.DevUtils
import dev.utils.app.HandlerUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author：Houge
 * @date：2022/1/16 13:15
 * @desc：通用加载弹窗
 */
class LoadingModel(private val context: Context? = null) : ILoading {

    private var _loadingDialog: MiniLoadingDialog? = null

    /**
     * 展示加载弹窗
     */
    override fun showLoading() {
        try {
            HandlerUtils.postRunnable {
                createLoadingDialog()
                setMessage("请稍候……")
                if (context is Activity) {
                    if (!context.isFinishing) {
                        _loadingDialog?.show()
                    }
                } else if (context is Fragment) {
                    if (context.activity?.isFinishing == false) {
                        _loadingDialog?.show()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun dismissLoading() {
        try {
            GlobalScope.launch(Dispatchers.Main) {
                delay(400)
                _loadingDialog?.dismiss()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 创建加载弹窗
     */
    private fun createLoadingDialog() {
        if (_loadingDialog == null) {
            _loadingDialog = MiniLoadingDialog(context ?: DevUtils.getTopActivity())
        }
    }

    /**
     * 设置弹窗文本内容
     */
    fun setMessage(msg: String) {
        createLoadingDialog()
        _loadingDialog?.updateMessage(msg)
    }
}